#include "argparser.h"
#include "filehandler.h"

#define MAXSIZE 4396 //冥冥之中自有7意

#define N 18

FILE *sfp;

//定向查找处理后的节点
char *getParameterByName(char *str,Command *head);
//初始化参数处理
Command *doArgParse(int argc, char** argv);
void doCount(char *command,char *parameter);

int main(int argc,char** argv)
{
	Command *head=doArgParse(argc,argv);
    char *output_file=getParameterByName("-o",head);
    char *stopword_file=getParameterByName("-s",head);
    if(stopword_file!=NULL)
    {
        if((sfp=fopen(stopword_file,"r"))==NULL)
        {
            fprintf(stderr,"can't open stopword file\n");
            exit(-1);
        }
    }
    if(output_file!=NULL)
    {
        if(freopen(output_file,"w",stdout)==NULL)
        {
            fprintf(stderr,"can't open this file\n");
            exit(-1);
        }
    }

    for(head=head->next;head!=NULL;head=head->next)
    {
        doCount(head->command,head->parameter);
    }
    return 0;
}

Command *doArgParse(int argc, char** argv)
{
    int i;
    char *coms[]={"-c","-w","-l","-a","-ca","-wa","-la","-cw","-cl","-wl","-cwa","-cla","-wla","-cwl","-cwla","-o","-e","-s"};
    // 初始化Comand链表的头节点
    Command *head = initCommand();
	// 自定义Command	
    for(i=0;i<N;i++)
    {
        putCommand(head, strdup(coms[i]), strdup("help"), FALSE, TRUE);
    }
    // 创建lexer 将当前的lexer与argc，argv传入
	Lexer l = initLexer(l, argc, argv);
	// 初始化parameterInterpreter，将初始化过的Lexer和Command链表的头节点传入
	ParameterInterpreter pi = initParameterInterpreter(&l, head);
	// 调用handleParamter(&pi) 返回所有处理结果 
	Command *result = handleParameter(&pi);
	// 调用getTriggeredComandList 将命令行中出现了的参数返回
	Command *a = getTriggeredComandList(result);
	// 测试用。。。
#ifdef DEBUG
	replCommandList(a);
#endif
    return a;
}

char *getParameterByName(char *str,Command *head)
{
    for(head=head->next;head!=NULL;head=head->next)
    {
        if(!strcmp(head->command,str))
        {
            return head->parameter;
        }
    }
    return NULL;
}
void doCount(char *command,char *parameter)
{
    FILE *fp=NULL;
    char *cp;
    if(!strcmp(command,"-o"))return;
    if(!strcmp(command,"-s"))return;
    if((fp=fopen(parameter,"r"))==NULL)
    {
        return;
    }
    else 
    {
        fprintf(stdout,"%s\n",parameter);
    }
    if((cp=strstr(command,"c"))!=NULL)
    {
        fprintf(stdout,"charate:%d\n",charateCount(fp));
    }
    if((cp=strstr(command,"w"))!=NULL)
    {
        if(sfp!=NULL)
        {
            fprintf(stdout,"word with stopword:%d\n",countWithStopWord(sfp,fp,"#"));
        }
        else 
        {
            fprintf(stdout,"word:%d\n",wordCount(fp));
        }
    }
    if((cp=strstr(command,"l"))!=NULL)
    {
        fprintf(stdout,"line:%d\n",lineCount(fp));
    }
    fclose(fp);
}